import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;

import javax.swing.JFrame;


public class View extends Observable implements ActionListener {
	
	// Windows
	MainWindow mw;
	NewUserWindow nuw;
	ChartWindow cw;
	WeightEntryWindow wew;
	
	// Constructor
	public View(Model model) {
		System.out.println("View started");
	}

	// Show Various Views
	public void showMainView() {
		mw = new MainWindow();
		mw.setVisible(true);
		mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// register main window notifications
		mw.setCloseActionListener(this);
//		mw.setLoginActionListener(this);
		mw.setChartActionListener(this);
		mw.setEnterWeightActionListener(this);
		
		// Can do some with anonymous class... 
		mw.setLoginActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				View.this.showNewUserView();
			}
			
		});
				
	}
		
	public void showNewUserView() {
		nuw = new NewUserWindow();
		nuw.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		nuw.setVisible(true);
		
		// register controller notifications
//		nuw.addNewUserListener(this);		

		// Alternate way of getting message to Controller
		nuw.addNewUserListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				View.this.setChanged();
				View.this.notifyObservers("NEW_USER:" + View.this.nuw.getUserText());
				View.this.nuw.dispose();							
			}
			
		});		

		
	}
	
	public void showChartView() {
		cw = new ChartWindow();
		cw.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		cw.setVisible(true);
		
		//chart window has no controller notifications
	}
	
	public void showWeightEntryWindow() {
		wew = new WeightEntryWindow();
		wew.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		wew.setVisible(true);
		
//		wew.addNewWeightListener(this);
		wew.addNewWeightListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				View.this.setChanged();
				View.this.notifyObservers("ADD_WEIGHT:" + View.this.wew.getWeight() + ":" + View.this.wew.getDate());
				View.this.wew.dispose();
			}
			
		});
	}
	
	// main view event processor
	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println("VIEW Event: " + e.getActionCommand() + ":" + e.paramString());
		
		
		if (e.getActionCommand().equalsIgnoreCase("Chart")) {
			showChartView();
		}
		
//		if (e.getActionCommand().equalsIgnoreCase("New User")) {
//			showNewUserView();
//		}
		
//		if (e.getActionCommand().equalsIgnoreCase("Log In")) {
//			setChanged();
//			notifyObservers("NEW_USER:" + nuw.getUserText());
//			nuw.dispose();			
//		}
		
		if (e.getActionCommand().equalsIgnoreCase("Close")) {
			setChanged();
			notifyObservers("SHUTDOWN:");
			mw.dispose();
		}
		
		if (e.getActionCommand().equalsIgnoreCase("Enter Weight")) {
			showWeightEntryWindow();
		}
	}
	
}
